package cn.zkw.controller.back;

import cn.zkw.service.*;
import cn.zkw.util.action.AbstractAction;
import cn.zkw.vo.Article;
import cn.zkw.vo.Comment;
import cn.zkw.vo.Label;
import cn.zkw.vo.User;
import com.sun.deploy.util.ArrayUtil;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/back/article")
public class ArticleController extends AbstractAction {
    @Autowired
    ArticleService articleService;

    @Autowired
    UserService userService;

    @Autowired
    SortService sortService;

    @Autowired
    LabelService labelService;

    /**
     * webapp分页加载接口
     * @param nextPage
     * @return
     */
    @RequestMapping(value = "/android/page",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public @ResponseBody Object android_page(Integer nextPage,String keyword){
        System.out.println(nextPage);
        JSONObject jsonObject = new JSONObject();
        List<Article> articles = articleService.splitArticle(nextPage);
        if(keyword!=null && "".equals(keyword)==false){
            Map<String,Object> map = new HashMap<>();
            map.put("num",nextPage);
            map.put("keyword",keyword);
            System.out.println(map);
            articles = articleService.splitArticleByKeyWord(map);
        }
        return articles;
    }

    /**
     * webapp查看文章接口
     * @param article_id
     * @return
     */
    @RequestMapping(value = "/android/getArticle",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public @ResponseBody Object android_getArticle(Integer article_id){
        Article article = articleService.selectArticleById(article_id);
        return article;
    }

    /**
     * 增加文章浏览量
     * @param article
     * @return
     */
    @RequestMapping(path = "/addview",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object addView(@RequestBody Article article){
        JSONObject jsonObject = new JSONObject();
        System.out.println("****************************"+article);
        article.setArticle_views(article.getArticle_views()+1);
        if(articleService.updateView(article)){  //浏览量更新
            jsonObject.put("msg","success");
            jsonObject.put("code",200); //操作成功
        }else{
            jsonObject.put("msg","error");
            jsonObject.put("code",304);  //资源没有被修改
        }
        return jsonObject;
    }

    /**
     * 滚动加载
     * @param nextPage
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/page")
    public String splitArticle(Integer nextPage, Model model,HttpServletRequest request){
        if(nextPage ==null){
            nextPage = 0;
        }
        List<Article> articles = articleService.splitArticle(nextPage);
        model.addAttribute("articles",articles);  //获取文章
        //总数
        int count = articleService.getArticleAllNum();
        //总页数
        int pageNum = count / 5;
        model.addAttribute("pageNum",pageNum);
        if (pageNum > nextPage) {
            model.addAttribute("nextPage", nextPage + 5);
        }else{
            model.addAttribute("nextPage", nextPage + 5);
//            model.addAttribute("articles",null);  //获取文章
        }
        return "front/index";
    }

    /**
     * 根据文章类别滚动加载
     * @param nextPage
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/page2")
    public String splitArticle2(Integer nextPage, Model model,HttpServletRequest request){
        if(nextPage ==null){
            nextPage = 0;
        }
        Map<String,Object> map = new HashedMap();
        map.put("num",nextPage);
        Integer sort_id = (Integer) request.getSession().getAttribute("sort_id");
        map.put("sort_id",sort_id);
        System.out.println(map);
        List<Article> articles = articleService.splitArticleBySort(map);
        model.addAttribute("articles",articles);  //获取文章
        //总数
        int count = articleService.selectArticleAllNum_BySort(sort_id);
        //总页数
        int pageNum = count / 5;
        model.addAttribute("pageNum",pageNum);
        if (pageNum > nextPage) {
            model.addAttribute("nextPage", nextPage + 5);
        }else{
            model.addAttribute("nextPage", nextPage + 5);
        }
        return "front/index";
    }

    /**
     * 搜索框---根据关键字滚动加载
     * @param nextPage
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/page3")
    public String splitArticle3(Integer nextPage,Model model,HttpServletRequest request){
        if(nextPage ==null){
            nextPage = 0;
        }
        Map<String,Object> map = new HashedMap();
        map.put("num",nextPage);
        String keyword = (String) request.getSession().getAttribute("keyword");
        map.put("keyword",keyword);
        System.out.println(map);
        List<Article> articles = articleService.splitArticleByKeyWord(map);
        for(int i=0;i<articles.size();i++){  //关键字红色
            Article art = articles.get(i);
            art.setArticle_title(art.getArticle_title().replace(keyword,"<span style='color:#f15b6c'>"+keyword+"</span>"));
            art.setArticle_describe(art.getArticle_describe().replace(keyword,"<span style='color:#f15b6c'>"+keyword+"</span>"));
            articles.set(i,art);
        }
        model.addAttribute("articles",articles);  //获取文章
        //总数
        int count = articleService.selectArticleAllNum_ByKeyWord(map);
        //总页数
        int pageNum = count / 5;
        model.addAttribute("pageNum",pageNum);
        if (pageNum > nextPage) {
            model.addAttribute("nextPage", nextPage + 5);
        }else{
            model.addAttribute("nextPage", nextPage + 5);
        }
        return "front/index";
    }

    /**
     * 添加文章,,需要登录认证
     * @param article
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ModelAndView addArticle(Article article){
        User user =  userService.getUserByName(String.valueOf(SecurityUtils.getSubject().getPrincipal()));  //查询当前用户的id
        article.setUser_id(user.getUser_id());  //获取用户id
        article.setArticle_date(new Date());  //添加文章当前日期
        articleService.addArticle(article);  //执行添加
        String labels = article.getLabel_name(); //获取文章标签集合
        String labelarr[] = labels.split(",");  //根据逗号分割标签
        Label label = new Label();             //添加label  标签
        for(int i=0;i<labelarr.length;i++){
            label.setLabel_name(labelarr[i]);
            labelService.addLabel(article.getArticle_id(),label);       //保存标签与文章的关系
        }

        Integer article_id = article.getArticle_id();
        Map<String,Integer> map = new HashedMap();
        map.put("article_id",article_id);
        map.put("sort_id",article.getSort_id());
        if(sortService.addSet_article_sort(map)>=1){
            System.out.println("add success****************8");
        };
        System.out.println(article_id);
        return null;
    }

    /**
     *修改文章
     * @param article
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public ModelAndView updateArticle(Article article){
        articleService.updateArticle(article);
        sortService.deleteSetSort(article.getArticle_id());//删除文章与分类的关系
        Map<String,Integer> map = new HashMap<>();
        map.put("article_id",article.getArticle_id());
        map.put("sort_id",article.getSort_id());
        sortService.addSet_article_sort(map);   //添加文章与分类的关系

        labelService.deleteSetLabel(article.getArticle_id()); //删除该文章的标签
        String labels = article.getLabel_name(); //获取文章标签集合
        String labelarr[] = labels.split(",");  //根据逗号分割标签
        Label label = new Label();             //添加label  标签
        for(int i=0;i<labelarr.length;i++){
            label.setLabel_name(labelarr[i]);
            labelService.addLabel(article.getArticle_id(),label);       //保存标签与文章的关系
        }

        ModelAndView modelAndView = new ModelAndView("redirect:/back/updateArticle?article_id="+article.getArticle_id());
        return modelAndView;
    }

    /**
     * 文章删除,批量删除
     * @param checkbox
     * @return
     */
    @RequestMapping("/delete")
    public ModelAndView deleteArticle(int[] checkbox,HttpServletRequest request){
        List<Integer> list = new ArrayList<>();
        for (int i=0;i<checkbox.length;i++){
            list.add(checkbox[i]);
        }
        ModelAndView modelAndView = new ModelAndView("redirect:/back/article");
        int result = 0;

        for(int i=0;i<list.size();i++){     //删除文章图片
            Article article =  articleService.selectArticleById(list.get(i));
            if(article.getArticle_img()!=null){     // 如果该文章又图片，进行删除
                String filepath = article.getArticle_img();
                filepath = filepath.substring(9,filepath.length());
                File file  = new File(request.getServletContext().getRealPath(filepath));
                if(file.exists()){
                    file.delete();   //删除文件
                }
            }
        }

        result = articleService.deleteArticleSet(list);
        if(result > 0){
            request.getSession().setMaxInactiveInterval(3);
            request.getSession().setAttribute("message","删除了"+result+"条记录");
        }else {
            request.getSession().setMaxInactiveInterval(3);
            request.getSession().setAttribute("message","删除失败,请重试");
        }
        return modelAndView;
    }


    //文章图片上传,,给uedirot使用的
    @RequestMapping(value = "/uploadimage",method = RequestMethod.POST)
    public Object uploadImg(MultipartFile upfile, HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        String filename = upfile.getName();  //ueditor UUID生成图片名,,来自ueditor富文本编辑器
        String url = "/uploadFiles/atricleImg/"+filename;
        jsonObject.put("url",url);    //设置图片路径
        jsonObject.put("title",filename);  //图片名称
        jsonObject.put("original",filename);  //图片名称
        if(super.saveFile(upfile,filename,request)){  //保存图片
            System.out.println("保存成功");
            jsonObject.put("state","SUCCESS");
        }else{
            System.out.println("保存失败");
            jsonObject.put("state","ERROR");
        }
        return jsonObject;
    }


    @Override
    public String getType() {
        return null;
    }

    @Override
    public String getFileUploadDir() {
        return "/uploadFiles/atricleImg";
    }
}
